package com.juyu.miliao.api.service.whitepacket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.juyu.miliao.api.constant.UpdateUserRedisKey;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.vo.VideoWhiteUserVo;
import com.juyu.miliao.api.service.AppKeyService;
import com.juyu.miliao.api.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static java.util.stream.Collectors.toList;

/**
 * @Auther: 卜加超
 * @Date: 2019/2/13 11:34
 * @Description:
 */
@Service("donkeyFriendService")
public class DonkeyFriendService {

    @Resource
    private AppKeyService appKeyService;

    @Resource
    private UserInfoDao userInfoDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public List<VideoWhiteUserVo> getListByUserId(String type, Integer page, Integer pageSize) {

        int startNum = PageUtil.getOffset(page, pageSize);
        int endNumber = (startNum+pageSize)-1;
        //驴友redis中的key值
        String key = UpdateUserRedisKey.DKEYFRIEND +type;
        Set<String> userSet =null;
        //判断驴友的key是否存在 如果存在直接拿到redis中的set集合
        if(stringRedisTemplate.hasKey(key)){
             userSet =stringRedisTemplate.opsForZSet().reverseRange(key,startNum,endNumber);
        }else{
            //如果不存在 根据type查询返回appkey对象
            Appkey appKey = appKeyService.getAppKeyByKey(type);
            List<User> users = null;
            if(appKey!= null){
                //取出appkey 中的value值用“，”分割 拿到里面的userId 转成list
                List<String> donkeyFriendUserId =  Arrays.asList(appKey.getValue().split(",")) ;
                //把集合中的String类型转变成long类型
                List<Long> userIds = donkeyFriendUserId.stream().map(Long::parseLong).collect(toList());
                //根据ids 查出List<User>集合 然后批量放入到驴友的redis中
                List<User> hotUserList = userInfoDao.getHotUserList(userIds);
                Set<ZSetOperations.TypedTuple<String>> hashSet = new HashSet<>();
                for (User user:hotUserList) {
                    DonKeyFriendZset donKeyFriendZset = new DonKeyFriendZset(JSONObject.toJSONString(user),1);
                    hashSet.add(donKeyFriendZset);
                }
                if(hashSet!=null){
                    stringRedisTemplate.opsForZSet().add(key,hashSet);
                    stringRedisTemplate.expire(key,10,TimeUnit.MINUTES);
                }

                userSet =stringRedisTemplate.opsForZSet().reverseRange(key,startNum,endNumber);
            }
        }
        List<VideoWhiteUserVo> list = new ArrayList<>();
            //判断set集合中是否有值 如果有值
        if(userSet!=null && userSet.size()>0){
            //便历集合把相应的字段放到vo中最终存到list中返回
            for (String videoUser: userSet) {
                VideoWhiteUserVo videoWhiteUserVo = new VideoWhiteUserVo();
                 JSONObject json = JSONObject.parseObject(videoUser);
                long userId = Long.parseLong(JSONPath.eval(json, "$.userId")+"");
                if(userId != 0){
                     videoWhiteUserVo.setUserId(userId);
                 }
                 String birthday = JSONPath.eval(json, "$.birthday") + "";

                if(birthday!= null){
                    videoWhiteUserVo.setBirthday(birthday);
                }
                 String city = JSONPath.eval(json, "$.city") + "";
                if(city != null){
                    videoWhiteUserVo.setCity(city);
                }
                String name = JSONPath.eval(json, "$.nickName") + "";
                if(name != null){
                    videoWhiteUserVo.setName(name);
                }
                String icon = JSONPath.eval(json, "$.icon") + "";
                if(city != null){
                    videoWhiteUserVo.setIcon(icon);
                }
                String signature = JSONPath.eval(json, "$.signature") + "";
                if(signature != null){
                    videoWhiteUserVo.setSignature(signature);
                }
                String realName = JSONPath.eval(json, "$.realName") + "";
                if(realName != null){
                    videoWhiteUserVo.setRealName(realName);
                }
                int sex =Integer.parseInt(JSONPath.eval(json, "$.sex") + "");
                if(sex != 0){
                    videoWhiteUserVo.setSex(sex);
                }
                list.add(videoWhiteUserVo);
            }
            return list;
        }else{
            return new ArrayList<>();
        }



    }


    class DonKeyFriendZset implements ZSetOperations.TypedTuple<String> {

        String value;

        double score;

        public DonKeyFriendZset(String value, double score) {

            this.value = value;

            this.score = score;
        }

        @Override
        public String getValue() {
            return value;
        }

        @Override
        public Double getScore() {
            return score;
        }

        @Override
        public int compareTo(ZSetOperations.TypedTuple<String> o) {

            DonKeyFriendZset o1 = (DonKeyFriendZset) o;

            return new Double(this.score).compareTo(o1.getScore());

        }
    }
}
